import java.io.IOException;

public class Pop3Service extends MailService {


  public Pop3Service(String user, String password, String host, int port) {
    super();
    this.user = user;
    this.host = host;
    this.password = password;
    this.port = port;
  }



  private void login() {
    sendCommand("USER " + user);
    readBufferLine();
    sendCommand("PASS " + password);
    readBufferLine();
  }

  private int getNumberOfMessages() {
    sendCommand("STAT " + password);
    String response = readBufferLine();
    // System.out.println(response);
    return Integer.parseInt(response.split(" ")[1]);
  }

  private void getMail(int number) {
    sendCommand("RETR " + number);
    System.out.println(readBufferLines("\\."));
  }

  private void logout() {
    sendCommand("QUIT");
    readBufferLine();
  }

  public boolean readEmails(int number) {
    try {
      connect(host, port);
      login();
      int maxNumber = getNumberOfMessages();
      if (number > 0 && number < maxNumber) {
        getMail(number);
      }
      logout();
      disconnect();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return true;
  }

  public int checkNumberOfEmails() {
    int maxNumber = -1;
    try {
      connect(host, port);
      login();
      maxNumber = getNumberOfMessages();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return maxNumber;
  }

  protected void finalize() throws Throwable {
    logout();
    disconnect();
  }
}
